package com.huangd.platform.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


//交换机队列等
@Configuration
@Slf4j
public class RabbitConfig {
    @Autowired
    private CachingConnectionFactory connectionFactory;
    private final static String DELAY_EXCHANGE = "push";
    private final static String DELAY_QUEUE = "push";

    @Bean
    public RabbitAdmin rabbitadmin(CachingConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //消息转换器
        rabbitTemplate.setMessageConverter(converter());
        //生产这confirm
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
            if (b) {
                log.info("消息发送成功 ->{}", correlationData.getReturnedMessage());
            } else {
                log.error("发送失败原因-> 消息:{}, 原因:{}", correlationData.getReturnedMessage(), s);
            }
        });
        //消息回调
        //开启强制回调
        rabbitTemplate.setMandatory(true);
        //设置消息回调
        rabbitTemplate.setReturnCallback((message, i, s, s1, s2) -> log.error("消息->{} 路由失败", message));
        return rabbitTemplate;
    }

    @Bean
    public MessageConverter converter() {
        return new Jackson2JsonMessageConverter();
    }
}